//
//  AppDelegate.m
//  JinFuThree
//
//  Created by 毛韶谦 on 2018/8/29.
//  Copyright © 2018年 毛韶谦. All rights reserved.
//

#import "AppDelegate.h"
#import "RootTabBarController.h"
#import <IQKeyboardManager.h>
#import "FMDeviceManager.h"

@interface AppDelegate ()<UIApplicationDelegate, JPUSHRegisterDelegate>

@property (nonatomic, strong)UIApplication *application;

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    self.application = application;
    [self initUI];
    [self updateData];
    [self settingJPushWithOptions:launchOptions];
    return YES;
}

-(void)initUI {
    
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.window.backgroundColor = [UIColor whiteColor];
    if ([Common loginState]) {//进入主控制器
        RootTabBarController *tabBarController = [[RootTabBarController alloc] init];
        self.window.rootViewController = tabBarController;
    }else { //登录
        self.window.rootViewController = [[Mediator sharedInstance] login_mainViewController];
    }
    [self.window makeKeyAndVisible];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateData) name:@"updateData_getAreaData" object:nil];
    [self initTongDun];
    
    IQKeyboardManager *manager = [IQKeyboardManager sharedManager];
    manager.shouldResignOnTouchOutside = YES;
    manager.shouldToolbarUsesTextFieldTintColor = NO;
    manager.enableAutoToolbar = NO;
    manager.keyboardDistanceFromTextField = 100;
}

-(void)updateData{
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [self getAreaData];
    });
}

-(void)getAreaData{
    
    [ASJF_Service getAreaData];
}

- (void)applicationWillResignActive:(UIApplication *)application {
    
    self.application = application;
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    
    self.application = application;
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    
    self.application = application;
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    
    self.application = application;
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


- (void)applicationWillTerminate:(UIApplication *)application {
    
    self.application = application;
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}





- (void)initTongDun {
    
    // 获取设备管理器实例
    FMDeviceManager_t *manager = [FMDeviceManager sharedManager];
    
    // 准备SDK初始化参数
    NSMutableDictionary *options = [NSMutableDictionary dictionary];
    
    /*
     * SDK具有防调试功能，当使用xcode运行时(开发测试阶段),请取消下面代码注释，
     * 开启调试模式,否则使用xcode运行会闪退。上架打包的时候需要删除或者注释掉这
     * 行代码,如果检测到调试行为就会触发crash,起到对APP的保护作用
     */
    // 上线Appstore的版本，请记得删除此行，否则将失去防调试防护功能！
    [options setValue:@"allowd" forKey:@"allowd"];  // TODO
#warning 测试使用
    // 指定对接同盾的测试环境，正式上线时，请删除或者注释掉此行代码，切换到同盾生产环境
    if (ApplicationEnvironmentProduction) {
        [options setValue:@"sandbox" forKey:@"product"]; // @"env"
    }else {
        [options setValue:@"sandbox" forKey:@"env"]; // @"env"
    }
    // 此处替换为您的合作方标识
    [options setValue:@"asfenqi" forKey:@"partner"];
    
    // 使用上述参数进行SDK初始化
    manager->initWithOptions(options);
    
}
- (void)settingJPushWithOptions:(NSDictionary *)launchOptions {
    JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
    entity.types = JPAuthorizationOptionAlert|JPAuthorizationOptionBadge|JPAuthorizationOptionSound;
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
    }
    [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
    NSString *appKey = @"5793ce821478d4c40eba4eee";
    NSString *channel = [NSString stringWithFormat:@"ios3.0"];
    [JPUSHService setupWithOption:launchOptions appKey:appKey
                          channel:channel
                 apsForProduction:ApplicationEnvironmentProduction
            advertisingIdentifier:nil];
}
- (void)setAlias {
    NSMutableDictionary *mutDic = [QuickDataLocalStorageTool QuickDataLocalStorageToolUserInfoRead];
    if (mutDic[@"UserPhone"]) {
        [JPUSHService setAlias:mutDic[@"UserPhone"] completion:^(NSInteger iResCode, NSString *iAlias, NSInteger seq) {
        } seq:1];
    }
    [JPUSHService crashLogON];
}
#pragma mark- JPUSHRegisterDelegate
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler  API_AVAILABLE(ios(10.0)){
    NSDictionary * userInfo = notification.request.content.userInfo;
    [[Mediator sharedInstance] getMessageNumWhenApplication:self.application didReceiveRemoteNotification:userInfo window:self.window];
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
    }
    completionHandler(UNNotificationPresentationOptionAlert);
}
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void(^)(void))completionHandler  API_AVAILABLE(ios(10.0)){
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    [[Mediator sharedInstance] getMessageNumWhenApplication:self.application didReceiveRemoteNotification:userInfo window:self.window];
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
    }
    completionHandler();
}
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    [[Mediator sharedInstance] getMessageNumWhenApplication:application didReceiveRemoteNotification:userInfo window:self.window];
    [JPUSHService handleRemoteNotification:userInfo];
    completionHandler(UIBackgroundFetchResultNewData);
}
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    NSLog(@"注册APNs成功并上报DeviceToken%@",deviceToken);
    [JPUSHService registerDeviceToken:deviceToken];
    [self setAlias];
}
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    NSLog(@"did Fail To Register For Remote Notifications With Error: %@", error);
}



@end
